var http = require("http");
// const os = require("os");
var server = http.createServer();
var requestCounter = 0;
var requestMap = {};
var requestCallback = function() {};

function addRequest(request_id, request, response) {
  requestMap[request_id] = { request, response };
}

function setRequestCallback(callback) {
  requestCallback = callback;
}

function sendResponse(request_id, content) {
  var response = requestMap[request_id].response;
  response.write(content);
  response.end();
  delete requestMap[request_id];
}

server.on("request", function (request, response) {
  requestCounter++;
  addRequest(requestCounter, request, response);
  console.log("收到客户端的请求了，请求路径是：" + request.url);
  requestCallback(requestCounter, request);

  // response.write("hello");
  // response.write(" nodejs ");
  // response.write(os.platform());
  // response.end();
});

server.listen(3000, function () {
  console.log("服务器启动成功了，访问网页可以通过 http://127.0.0.1:3000/");
});

module.exports = {
  sendResponse,
  setRequestCallback
};